﻿using System;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using System.Web;
using System.Web.UI;

using SiteUnity.Layers.Application.Contents;
using SiteUnity.Layers.Entity.PageItems.Contents;
using SiteUnity.Frame.Common.Tools.Class;
using SiteUnity.Layers.Entity.Users;
using SiteUnity.Layers.Application.Users;
using SiteUnity.Frame.Common.UITools;
using SiteUnity.Frame.Common;
using SiteUnity.Layers.Application;
using SiteUnity.Layers.Application.BaseClasses;
using SiteUnity.Layers.Entity.UITools;
using SiteUnity.Frame.Common.Tools;

namespace SiteUnity.Frame.Modules
{
    [ToolboxData("<{0}:Comments runat=server/>")]
    public class Comments : BaseWebControl
    {
        public bool HideComments { get; set; }
        public bool HideTitle { get; set; }

        TextBox Name = new TextBox();
        TextBox Email = new TextBox();
        TextBox Website = new TextBox();
        TextBox Comment = new TextBox();
        Button Post = new Button();

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            generatePostComment();

            if (Page.IsPostBack && Post.isClicked)
                Post.onClick();
        }

        private void generatePostComment()
        {
            if (!HideTitle)
            {
                Container header = new Container();
                header.ID = "titlePostComment";
                header.Tag = ContainerType.h2;
                header.InnerText = "Post a comment";
            }
            
            Name.ID = "Name";
            Name.ShowTitle = true;
            Name.isRequired = true;
            Name.CssClass += " validate[required] ";
            this.Controls.Add(Name);
            
            Email.ID = "Email";
            Email.ShowTitle = true;
            Email.isRequired = true;
            Email.CssClass += " validate[required,custom[email]] ";
            this.Controls.Add(Email);

            Website.ID = "Website";
            Website.ShowTitle = true;
            Website.CssClass += " validate[custom[url]] ";
            this.Controls.Add(Website);
            
            Comment.ID = "Comment";
            Comment.ShowTitle = true;
            Comment.TextMode = System.Web.UI.WebControls.TextBoxMode.MultiLine;
            Comment.isRequired = true;
            Comment.CssClass += " validate[required] ";
            this.Controls.Add(Comment);
            
            Post.ID = "postcomment";
            Post.Text = "Post Comment";
            Post.CssClass = "button";
            Post.onClick += new onClick(PostButton_Click);
            this.Controls.Add(Post);
        }

        private void PostButton_Click()
        {
            string message = string.Empty;

            try
            {
                Control[] controls = { Name, Email, Comment };

                if (!UIValidation.isValid(controls))
                    message = "Please fill the requered fields";
                else
                {
                    message = "I received your message. I will contact as soon as possible ;)";

                    Content content = new Content();
                    content.ContentText = Comment.Text;
                    content.ContentTitle = string.Empty;
                    content.TypeID = ContentType.CommentWaiting;

                    content = ContentManager.insertContent(content);

                    if (!UserManager.User.Exists)
                    {
                        User user = new User();
                        string fullName = Name.Text;
                        user.Name = Formatter.getName(fullName, ' ');
                        user.Surname = Formatter.getSurname(fullName, ' ');
                        user.Website = Website.Text;
                        user.Email = Email.Text;

                        UserManager.User = UserManager.insertUser(user);
                    }
                    UserPageItem userPageItem = new UserPageItem();
                    userPageItem.userGuid = UserManager.User.Guid;
                    userPageItem.pageItemGuid = content.Guid;

                    UserManager.insertUserPageItem(userPageItem);
                }
            }
            catch
            {
                message = "Opps... An error was occured. Please try again.";
            }

            Container divMessage = new Container();
            divMessage.Tag = ContainerType.h4;
            divMessage.InnerText = message;
            this.Controls.Add(divMessage);
        }

        private void generateComments(HtmlTextWriter output)
        {
            List<Content> comments = ClassCollection.FindAll(ContentManager.getContentByPage(), "TypeID", ContentType.CommentApproved);
            if (comments.Count == 0)
                return;

            List<User> users = UserManager.getUserByPage();
            List<UserPageItem> userpageitems = UserManager.getUserPageItemByPage();

            output.RenderBeginTag(HtmlTextWriterTag.H2);
            output.Write(comments.Count + " Comments");
            output.RenderEndTag();

            output.AddAttribute(HtmlTextWriterAttribute.Id, "commentList");
            output.RenderBeginTag(HtmlTextWriterTag.Ol);
            foreach (Content content in comments)
            {
                UserPageItem commentUserPageItem = ClassCollection.Find(userpageitems, "pageItemGuid", content.Guid);
                User commentUser = ClassCollection.Find(users, "Guid", commentUserPageItem.userGuid);

                output.RenderBeginTag(HtmlTextWriterTag.Li);

                //picture here
                output.AddAttribute(HtmlTextWriterAttribute.Style, "margin:10px;");
                output.RenderBeginTag(HtmlTextWriterTag.P);
                output.Write(string.Format("<a href='#'><img src='{0}' alt='' width='56' height='56'/></a>", "/Assets/images/avatar.png"));
                output.RenderEndTag();

                output.RenderBeginTag(HtmlTextWriterTag.P);

                output.RenderBeginTag(HtmlTextWriterTag.Cite);
                output.Write(string.Format("By <a href='{0}' target='_blank'>{1} {2}</a> {3} &mdash; ",
                    Formatter.Url(commentUser.Website),
                    commentUser.Name,
                    commentUser.Surname,
                    Formatter.calculateDateDifference(content.Date)));
                output.RenderEndTag();

                output.Write(content.ContentText);
                output.RenderEndTag();

                output.RenderEndTag();
            }
            output.RenderEndTag();
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            if (!HideComments)
            {
                StringBuilder sb = new StringBuilder();
                HtmlTextWriter htw = new HtmlTextWriter(new StringWriter(sb, CultureInfo.InvariantCulture));
                generateComments(htw);

                output.Write(sb.ToString());
            }
            base.RenderContents(output);
        }
    }
}
